import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service";
import { NotificationService } from "../../shared/utils/notification.service";
import { config } from '../../shared/smartadmin.config';
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { throttleable } from '@swimlane/ngx-datatable/release/utils';


declare var $: any;
@Component({
	selector: 'sa-report-form',
	templateUrl: './report-form.component.html',
	styleUrls: ['./report-form.css']
})
export class ReportFormComponent implements OnInit {
	validatorOptions = {
		excluded:[":disabled"],
		feedbackIcons: {
			valid: 'glyphicon glyphicon-ok',
			invalid: 'glyphicon glyphicon-remove',
			validating: 'glyphicon glyphicon-refresh'
		},
		fields: {
			polishInstaller: {
				validators: {
					notEmpty: {
						message: '请选择项目名称'
					}
				}
			},
			startTime:{
				trigger:"change",
				validators: {
					notEmpty: {
						message: '请选择开始时间'
					},
					date: {
                        format: 'YYYY-MM-DD',
                        message: '请输入正确的时间,例如2018-01-00'
                    }
				}
			},
			endTime:{
				trigger:"change",
				validators: {
					notEmpty: {
						message: '请选择完成时间'
					},
					date: {
                        format: 'YYYY-MM-DD',
                        message: '请输入正确的时间,例如2018-01-00'
                    }
				}
			}
		}
	};
	constructor(private jsonApiService: JsonApiService, private notificationService: NotificationService, private router: Router, private activatedRoute: ActivatedRoute) {
		activatedRoute.queryParams.subscribe(queryParams => {});
	}
	tableData:any[] = []; //table数据
	totalCounts:number = 0; //分页总条数
	curPage:number = 1; //分页当前页
	pageSize:number = 10; //内置的分页每页条数
	startTime:string = '';//过滤条件:开始时间
	endTime:string = '';//过滤条件:结束时间
	searchKey:string = ''; //过滤条件:keyword
	selectedCompanyName = '';//过滤条件:公司名称
	selectedCompanyId = '';//过滤条件:公司ID
	btnNum:string = 'sensorProblem';
	tabNumberList:any = [];	//tab数据数组
	TimeSuggest: any = ''
	//订单分类汇总
	loadSortData(reqdata){
		this.jsonApiService.http("reportStatis/countReportRecordByType.html", reqdata).subscribe(data => {
			if(data&&data.data){
				this.tabNumberList = data.data;
			}
		})
	}
	//table   分页
	load(){
		var dataTime = $('#datetimepicker1').val();
		if(!dataTime){
			this.jsonApiService.message('请选择查询数据的时间');
			return;
		}
		this.startTime = this.GetMonday(dataTime);
		this.endTime = this.getNextDate(this.startTime,6);

		let timeCheck=common.correctTimeParams(this.startTime,this.endTime,0);
		if(!timeCheck.status){
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		
		const param = {
			"pageSize": this.pageSize,
			"nowPage": this.curPage,
			"parameters": {
				startTime:this.startTime + ' 00:00:00',
				endTime:this.endTime + ' 00:00:00',
				companyId:this.selectedCompanyId,
				searchKey:this.searchKey.trim(),
				type:'',
			}
		};
		switch (this.btnNum){
			case 'sensorProblem':
				param.parameters.type = '0';		//传感器问题统计
				break;
			case 'gpsProblem':
				param.parameters.type = '1';		//GPS问题统计
				break;
			case 'repairCount':
				param.parameters.type = '2';	//待维修报表统计	
				break;
			case 'orderCount':
				param.parameters.type = '3';		//订单周报统计
				break;
			case 'deviceOffLine':
				param.parameters.type = '4';		//红狮传感器问题统计
				break;
			default:
				break;
		}
		let reqdata = 'gridPager=' + JSON.stringify(param);
		this.loadSortData(reqdata);
		this.jsonApiService.http("reportStatis/list.html", reqdata).subscribe(data => {
			if(data&&data.exhibitDatas){
				for(let item of data.exhibitDatas){
					if(item.percentage){
						item.percentage = this.toPercent(item.percentage)
					}
					if(item.lastWeekPercentage && this.btnNum != 'repairCount'){
						item.lastWeekPercentage = this.toPercent(item.lastWeekPercentage)
					}
					if(item.chainRatio){
						if(item.chainRatio == 0){
							item.chainRatio = 0
						}else if(item.chainRatio > 0){
							item.isUp = true
							if(this.btnNum != 'repairCount'){
								item.chainRatio = this.toPercent(item.chainRatio)
							}
						}else{
							item.isUp = false
							if(this.btnNum != 'repairCount'){
								item.chainRatio = this.toPercent(item.chainRatio)
							}
						}
						
					}
					if(item.normalRate){
						item.normalRate = this.toPercent(item.normalRate)
					}
					if(item.exceptionRate){
						item.exceptionRate = this.toPercent(item.exceptionRate)
					}
				}
				this.tableData = data.exhibitDatas;
				this.totalCounts = data.recordCount;
			}
		})
	}
	//转换百分比
	toPercent(point){
		return (Math.round(point * 10000) / 100) + '%';
	}
	//删除所选时间
	del_date(){
		this.startTime = '';
		this.endTime ='';
		$("#datetimepicker1").val('').change();
		$("#datetimepicker1").datetimepicker("setStartDate", null);
		$('.TimeSuggest').val('')
		this.TimeSuggest = ''
	}
	//分页回调
	paginate(e){
		this.curPage = e.page+1;
		this.pageSize = e.rows;
		this.load();
	}
	//查询
	table_search(){
		this.curPage = 1;
		this.load();
	}
	//数据分类按钮点击事件
	btnClick(type){
		this.btnNum = type;
		this.curPage = 1;
		this.load();
	}
	//刷新
	refresh(){
		this.load();
	}

	/*
	 *  数据导出
	 */
	exportReport(){
		var dataTime = $('#datetimepicker1').val();
		if(!dataTime){
			this.jsonApiService.message('请选择导出数据的时间');
			return;
		}
		this.startTime = this.GetMonday(dataTime);
		this.endTime = this.getNextDate(this.startTime,6);
		const param = {
			'startTime':this.startTime + ' 00:00:00',
			'endTime':this.endTime + ' 00:00:00',
			'companyId':this.selectedCompanyId,
			'searchKey':this.searchKey.trim(),
			'type':'',
		};
		switch (this.btnNum){
			case 'sensorProblem':
				param.type = '0';		//传感器问题统计
				break;
			case 'gpsProblem':
				param.type = '1';		//GPS问题统计
				break;
			case 'repairCount':
				param.type = '2';	//待维修报表统计	
				break;
			case 'orderCount':
				param.type = '3';		//订单周报统计
				break;
			case 'deviceOffLine':
				param.type = '4';		//红狮传感器问题统计
				break;
			default:
				break;
		}	
		common.exprotDataFile(param, 'param', config.BaseURL + 'gpsOrderController/exportOrderDataRecordFile.html')
	}
	
	//公司选中回调
	companySelected(val) {
		this.selectedCompanyId = val.companyId;
		this.selectedCompanyName = val.companyName;
	}
	ngOnInit() {
		System.import('script-loader!select2/dist/js/select2.min.js').then(()=>{
            System.import('assets/js/select2-zh-CN.js').then(()=>{
                this.initAllRepairPoint().then(()=>{ 
					this.initRepairPointSelect2();
					this.initAllSelect2();
				});
            })
        })
		this.initDate().then(() => {
			this.load();
		});
	}
	companyList:any = [];// 项目名称
	// 项目
    initAllRepairPoint() {
        var that = this;
        return new Promise(function (resolve, reject) {
            that.jsonApiService.http("company/queryTopCompanyList.html",null).subscribe(data=> {
                if(data.success){
                    var companyList = data.data;
                    var selectdata = [];
                    for(var i = 0 ; i < companyList.length ; i++) {
                        var obj = {
                            id:companyList[i].id,
                            text:companyList[i].companyName,
                        }
                        selectdata[i] = obj;
                    }
                }
                that.companyList = selectdata;
                resolve();
            })
        })
	}
	// 项目配置
	initRepairPointSelect2() {
	    let that = this;
	    // 维修点-查询条件
        $("#companySelect2").select2({
            language : "zh-CN",
            placeholder :"请选择",
            allowClear : true,
            data: this.companyList
        }).on("select2:select", function (e){
            var data = e.params.data;
			that.selectedCompanyName = data.text;
			that.selectedCompanyId = data.id;
        });
	}
	// 删除项目
	delCompany() {
		this.selectedCompanyName = '';
		this.selectedCompanyId = '';
        //采用简单粗暴的方法清除;官方推荐的方法失效
        var str=$("<span class='select2-selection__placeholder'>请选择</span>");
        $('#companySelect2').val("");
        $("#select2-companySelect2-container").empty();
        $("#select2-companySelect2-container").attr("title","");
        $("#select2-companySelect2-container").prepend(str);
	}
	//初始化时间
	initDate() {
		let that = this;
		var date = new Date();
		var getDate,Suggest,month;
		return new Promise(function(resolve, error) {
			System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(() => {
				System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
					$("#datetimepicker1").datetimepicker({ //时间插件
						format: "yyyy-mm-dd",
						language: "zh-CN",
						autoclose: true,
						minView: 2,
					}).on("changeDate", function(e) {
						var dateTime = e.date;
						var time = common.getTimeMmss(dateTime);
						var timeList = time.substring(0,10);
						var GetMondayTime = that.GetMonday(timeList);
						Suggest = "统计范围为：周一[" + GetMondayTime + "] 之前所有数据";
						$('.TimeSuggest').val(Suggest)
						var nowTime = new Date().toLocaleDateString().replace(/\//g,"-");
						$("#datetimepicker1").datetimepicker("setEndDate", date);
						$("#datetimepicker1").change();
					});
					
					let nowDate = common.getNowTime().split(' ')[0];
					var time = nowDate.replace(/-/g,"/");
					
					$("#datetimepicker1").val(nowDate);
					var timeList = time.substring(0,10);
					var GetMondayTime = that.GetMonday(timeList);
					// Suggest = "统计时间段为：周一[" + GetMondayTime + "] 至 周日[" + that.getNextDate(GetMondayTime,6) +"]";
					Suggest = "统计范围为：周一[" + GetMondayTime + "] 之前所有数据";
					$("#datetimepicker1").datetimepicker("setEndDate", date);
					$('.TimeSuggest').val(Suggest)

					$("#workStartTime").datetimepicker({ //时间插件
                        format: "yyyy-mm-dd",
						language: "zh-CN",
						autoclose: true,
						minView: 2,
                    })
                    .on("changeDate", function(e) {
                        var date = e.date;
                        var time = common.getTimeMmss(date);
                        that.projectCount.startTime = $("#workStartTime").val() ;
                        $("#workEndTime").datetimepicker("setStartDate", time);
                        $("#workStartTime").change();
                    });
                    $("#workEndTime").datetimepicker({ //时间插件
                        format: "yyyy-mm-dd",
						language: "zh-CN",
						autoclose: true,
						minView: 2,
                    })
                    .on("changeDate", function(e) {
                        var date = e.date;
                        var time = common.getTimeMmss(date);
                        that.projectCount.endTime = $("#workEndTime").val() ;
                        $("#workStartTime").datetimepicker("setEndDate", time);
                        $("#workEndTime").change();
					});
					
					resolve();
				})
			})
		});
	}
	//获取第几周
	getMonthWeek(a, b, c) {
        /**
          * a = d = 当前日期
          * b = 6 - w = 当前周的还有几天过完(不算今天)
          * a + b 的和在除以7 就是当天是当前月份的第几周
          */
          var date = new Date(a, parseInt(b) - 1, c),
              w = date.getDay(),
              d = date.getDate();
         if(w==0){
             w=7;
         }
         var config={
             getMonth:date.getMonth()+1,
             getYear:date.getFullYear(),
             getWeek:Math.ceil((d + 6 - w) / 7),
         }
 		return config;
	}
    // 	获取指定日期的前几天或后几天  

    // date代表指定日期，格式：2018-09-27

    // day代表天数，-1代表前一天，1代表后一天
	getNextDate(date, day) { 
		var mills = new Date(Date.parse(date)).getTime();//获得毫秒数
		var dd = new Date(mills);
		var num = Math.abs(dd.getDate() + day);
	　　dd.setDate(num);
	　　var y = dd.getFullYear();
	　　var m = dd.getMonth() + 1 < 10 ? "0" + (dd.getMonth() + 1) : dd.getMonth() + 1;
	　　var d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate();
	　　return y + "-" + m + "-" + d;
	};
	//获取制定日期的周一日期
	GetMonday(time) {
		var dd = new Date(time);
		var week = dd.getDay(); //获取时间的星期数
		var minus = week ? week - 1 : 6;
		dd.setDate(dd.getDate() - minus); //获取minus天前的日期
		var y = dd.getFullYear();
		var m = dd.getMonth() + 1 < 10 ? "0" + (dd.getMonth() + 1) : dd.getMonth() + 1; //获取月份
		var d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate();
		return y + "-" + m + "-" + d;
	}





	/**
	 * 项目统计
	 */
	initAllSelect2(){
		var that = this;
		$("#polishSelect2").select2({
			language : "zh-CN",
            data: this.companyList
       	}).on("select2:select", function (e){
        	var data = e.params.data;
			$("#polishInstallerInput").val(data.text).change();
			that.projectCount.companyIds = data.text;
        });
	}
	getSelect2Value(id){
		var data = $(id).select2("data");
		var result = '';
		for(let item of data){
			result += item.id+",";
		}
		result = result.substring(0,result.length-1);
		return result;
	}
	projectCount: any ={
		companyIds: '',
		startTime: '',
		endTime: ''
	}
	projectExportReport(modal){
		$("#workEndTime").datetimepicker("setStartDate", null);
		$("#workStartTime").datetimepicker("setEndDate", null);
		$('#workStartTime').val('');
		$('#workEndTime').val('');
		$('#polishSelect2').val('');
		$('#polishInstallerInput').val('');
		this.projectCount.companyIds = '';
		this.projectCount.startTime = '';
		this.projectCount.endTime = '';
		$('.select2-selection__choice').remove();
		$("#projectCount").data('bootstrapValidator').resetForm();
		modal.show();
	}
	modalClose(modal){
		modal.hide();
	}
	//导出提交
	projectCountSubmit(modal){
		this.projectCount.companyIds = this.getSelect2Value('#polishSelect2');
		$('#projectCount').bootstrapValidator('validate'); //开启验证
		let isValid = $('#projectCount').data('bootstrapValidator').isValid();  //验证是否通过
		if(isValid){
			this.projectCount.startTime = this.projectCount.startTime + " 00:00:00";
			this.projectCount.endTime = this.projectCount.endTime + " 00:00:00";
			this.downLoad();
			modal.hide();
		}
	}

	//下载execl
	downLoad(){
		//导出1
		var form1 = $("<form>"); //定义一个form表单
		form1.attr("style", "display:none");
		form1.attr("target", "");
		form1.attr("method", "post");
		form1.attr("action", config.BaseURL + 'reportStatis/exportReportStatisList.html');
		var fileInput1 = $("<input>");
		fileInput1.attr("type", "hidden");
		fileInput1.attr("id", "fileName"); //设置属性的名字
		fileInput1.attr("name", "param"); //设置属性的名字
		fileInput1.attr("value", JSON.stringify(this.projectCount)); //设置属性的值
		$("body").append(form1); //将表单放置在web中
		form1.append(fileInput1);
		form1.submit(); //表单提交

		form1.remove();
	}

}	
